package com.example.demo.netty.c3;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @description:
 * @author: hhl
 * @createDate: 2024/1/25
 * @version: 1.0
 */
@Slf4j
public class CloseFutureClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new StringEncoder());
                    }
                }).connect(new InetSocketAddress("localhost", 8080));

//        channelFuture.addListener(
//                (ChannelFutureListener)future -> {
//                    Channel channel = future.channel();
//                    log.debug("futrue{}",future);
//                    channel.writeAndFlush("aaaa");
//                }
//        );
//        channelFuture.addListener(new ChannelFutureListener() {
//            @Override
//            public void operationComplete(ChannelFuture future) throws Exception {
//                Channel channel = future.channel();
//                    log.debug("{}",future);
//                    channel.writeAndFlush("aaaa");
//            }
//        });
//
        Channel channel = channelFuture.sync().channel();
        Thread thread = new Thread(
                () -> {
                    while (true) {
                        Scanner scanner = new Scanner(System.in);
                        String b = scanner.next();
                        if ("q".equals(b)) {
                            channel.close();
                            break;
                        }
                        channel.writeAndFlush(b);
                    }
                }
                , "input");
        boolean daemon = thread.isDaemon();
        thread.start();
        ChannelFuture closeFuture = channel.closeFuture();
        closeFuture.addListener(
                (ChannelFutureListener)close->{
                    Channel channel1 = close.channel();
                    log.debug("服务端关闭");
                    group.shutdownGracefully();
                }
        );
    }

}
